﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Fly.Serializers
{
    /// <summary>
    /// 二进制方式序列化对象
    /// </summary>
    public static class BinarySerializer
    {
        /// <summary>
        /// 序列化一个对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>The serialized object</returns>
        public static byte[] Serializer(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                return stream.ToArray();
            }
        }
        /// <summary>
        /// 序列化一个对象,并对序列化结果进行 Base64 位编码
        /// </summary>
        /// <param name="obj">需要序列化的对象</param>
        /// <returns></returns>
        public static string SerializerToBase64(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                byte[] bytes =stream.ToArray();
                if (bytes.Length > 0)
                {
                    return Convert.ToBase64String(bytes, Base64FormattingOptions.None);
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <param name="objectType">Object type</param>
        /// <param name="data">Data to deserialize</param>
        /// <returns>The resulting object</returns>
        public static object Deserializer(byte[] data, Type objectType)
        {
            if (data == null)
            {
                return null;
            }
            using (MemoryStream stream = new MemoryStream(data))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(stream);
            }
        }
    }
}
